package com.net.oil.shop;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.google.gson.Gson;
import com.net.oil.R;
import com.net.oil.app.Constant;
import com.net.oil.app.UserInfoManager;
import com.net.oil.base.BaseActivity;
import com.net.oil.car.MyCarActivity;
import com.net.oil.gaode.RoutePlanActivity;
import com.net.oil.http.AppUrl;
import com.net.oil.main.bean.HomePageInfoBean;
import com.net.oil.order.ReserveActivity;
import com.net.oil.shop.adapter.ShopBannerAdapter;
import com.net.oil.shop.bean.ShopDetailBean;
import com.net.oil.shop.contract.ShopDetailContract;
import com.net.oil.shop.presenter.ShopDetailPresenter;
import com.net.oil.user.LoginActivity;
import com.net.oil.util.DateFormat;
import com.net.oil.util.DisplayUtil;
import com.net.oil.util.SharedPreferencesKey;
import com.net.oil.util.SharedPreferencesUtil;
import com.net.oil.util.StringUtil;
import com.net.oil.util.glide.GlideUtil;
import com.net.oil.widget.BannerViewPager;
import com.net.oil.widget.ToastUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopDetailActivity extends BaseActivity<ShopDetailPresenter> implements ShopDetailContract.View {

    @BindView(R.id.toolbar_go_back)
    ImageView toolbarGoBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.shop_title)
    TextView shopTitle;
    @BindView(R.id.location_button)
    TextView locationButton;
    @BindView(R.id.shop_address)
    TextView shopAddress;
    @BindView(R.id.right_icon)
    ImageView rightIcon;
    @BindView(R.id.shop_phone)
    TextView shopPhone;
    @BindView(R.id.shop_banner)
    BannerViewPager shopBanner;
    @BindView(R.id.car_info_tv)
    TextView carInfoTv;
    @BindView(R.id.reserve_time_tv)
    TextView reserveTimeTv;
    @BindView(R.id.ok_button)
    Button okButton;
    @BindView(R.id.shop_time)
    TextView shopTime;
    @BindView(R.id.shop_detail_layout)
    RelativeLayout shopDetailLayout;
    @BindView(R.id.address_layout)
    RelativeLayout addressLayout;
    @BindView(R.id.banner_dot_group)
    RadioGroup bannerDotGroup;
    @BindView(R.id.ic_go)
    ImageView icGo;

    private ShopDetailBean shopDetailBean;
    private int carId = -1;     //预约选中的爱车id
    private int shopId = -1;     //店铺id

    private HomePageInfoBean.MycarBean mycarBean;
    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail);
        ButterKnife.bind(this);
        presenter = new ShopDetailPresenter(this);
        initView();
        initData();
    }

    private void initData() {
        carId = getIntent().getIntExtra(Constant.INTENT_CAR_ID, -1);
        String carType = getIntent().getStringExtra(Constant.INTENT_CAR_TYPE);
        if (carId != -1 && !TextUtils.isEmpty(carType)) {
            carInfoTv.setText(carType);
        } else {
            mycarBean = gson.fromJson(SharedPreferencesUtil.getStringParam(this, SharedPreferencesKey.MY_CAR, ""), HomePageInfoBean.MycarBean.class);
            if (mycarBean != null) {
                carId = mycarBean.getId();
                HomePageInfoBean.MycarBean.CarModelInfoBean modelInfoBean = mycarBean.getCarModelInfo();
                if (modelInfoBean != null) {
                    if (!TextUtils.isEmpty(modelInfoBean.getType())) {
                        carInfoTv.setText(modelInfoBean.getType());
                    }
                }
            }
        }

        shopId = getIntent().getIntExtra(Constant.INTENT_SHOP_ID_KEY, -1);      //店铺id
        if (shopId != -1) {
            showProgressDialog();
            presenter.getShopDetail(shopId);
        }


    }

    private void initView() {
        toolbarTitle.setText(R.string.shop_detail);

        shopBanner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                bannerDotGroup.check(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @OnClick({R.id.toolbar_go_back, R.id.shop_phone, R.id.car_info_tv, R.id.reserve_time_tv,
            R.id.ok_button, R.id.shop_detail_layout, R.id.address_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_go_back:
                finish();
                break;
            case R.id.address_layout:
                Intent intent = new Intent(this, RoutePlanActivity.class);
                if (shopDetailBean != null) {
                    intent.putExtra(Constant.INTENT_LNG, shopDetailBean.getLng());
                    intent.putExtra(Constant.INTENT_LAT, shopDetailBean.getLat());
                }
                startActivity(intent);
                break;
            case R.id.shop_phone:
                if (!StringUtil.isEmpty(shopPhone.getText().toString())) {
                    showCallDialog(shopPhone.getText().toString());
                } else {
                    ToastUtil.showErrorToast(this, "没有商家电话号码");
                }
                break;
            case R.id.car_info_tv:
                if (UserInfoManager.getInstance().isLogin()) {
                    Intent intent1 = new Intent(this, MyCarActivity.class);
                    intent1.putExtra(Constant.INTENT_SELECT_CAR_ID, carId);     //把选中的carId传入选择界面
                    startActivityForResult(intent1, Constant.DEFAULT_REQUEST);
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.reserve_time_tv:
                if (UserInfoManager.getInstance().isLogin()) {
                    selectData();
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.ok_button:
                if (carId == -1) {
                    ToastUtil.showErrorToast(this, "请选择车辆信息");
                } else if (StringUtil.isEmpty(reserveTimeTv.getText().toString())) {
                    ToastUtil.showErrorToast(this, "请选择预约时间");
                } else {
                    showProgressDialog();
                    presenter.reserveOrder(shopId, reserveTimeTv.getText().toString(), carId);
                }
                break;
            case R.id.shop_detail_layout:
                Intent intent2 = new Intent(this, ShopIntroduceActivity.class);
                intent2.putExtra(Constant.INTENT_SHOP_INTRODUCE_KEY, shopDetailBean.getBusinessDesc());
                startActivity(intent2);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            carId = data.getIntExtra(Constant.INTENT_SELECT_CAR_ID, -1);
            String carType = data.getStringExtra(Constant.INTENT_SELECT_CAR_INFO);
            if (!StringUtil.isEmpty(carType)) {
                carInfoTv.setText(carType);
            } else {
                carInfoTv.setText("");
            }
        }
    }

    /**
     * 获取商家详情成功
     *
     * @param shopDetailBean 商家详情数据
     */
    @Override
    public void getShopDetailSuccess(ShopDetailBean shopDetailBean) {
        dismissProgressDialog();

        if (shopDetailBean != null) {
            this.shopDetailBean = shopDetailBean;
        }

        if (!StringUtil.isEmpty(shopDetailBean.getName())) {
            shopTitle.setText(shopDetailBean.getName());
        }

        if (!StringUtil.isEmpty(shopDetailBean.getAddress())) {
            shopAddress.setText(shopDetailBean.getAddress());
        }

        if (!StringUtil.isEmpty(shopDetailBean.getPhone())) {
            shopPhone.setText(shopDetailBean.getPhone());
        }

        if (!TextUtils.isEmpty(shopDetailBean.getServiceStartTime()) && !TextUtils.isEmpty(shopDetailBean.getServiceEndTime())) {
            String serviceTime = "店铺服务时间：" + shopDetailBean.getServiceStartTime() + " - " + shopDetailBean.getServiceEndTime();
            shopTime.setText(serviceTime);
        }


        if (shopDetailBean.getImages() != null && shopDetailBean.getImages().size() > 0) {
            setShopBanner(shopDetailBean.getImages());
        }

    }

    /**
     * 获取商家详情失败
     */
    @Override
    public void getShopDetailFailed() {
        dismissProgressDialog();
    }

    /**
     * 预约成功
     */
    @Override
    public void reserveOrderSuccess() {
        dismissProgressDialog();
        reserveTimeTv.setText("");
        ToastUtil.showSuccessToast(this, "预约成功");
        startActivity(new Intent(this, ReserveActivity.class));
    }

    /**
     * 预约失败
     */
    @Override
    public void reserveOrderFailed() {
        dismissProgressDialog();
        ToastUtil.showErrorToast(this, "y预约失败");
    }

    private void showCallDialog(final String phoneNumber) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("联系商家");
        builder.setMessage(phoneNumber);
        builder.setPositiveButton("联系商家", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Uri uri = Uri.parse("tel:" + phoneNumber);
                Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

    private void setShopBanner(List<String> urlList) {
        List<ImageView> imageViews = new ArrayList<>();
        RadioGroup.LayoutParams buttonParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        buttonParams.setMargins(DisplayUtil.dip2px(5), 0,
                DisplayUtil.dip2px(5), 0);
        for (int i = 0; i < urlList.size(); i++) {
            ImageView imageView = new ImageView(this);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);

            GlideUtil.getInstance().loadImage(this, imageView, AppUrl.getImageUrl(urlList.get(i)), R.drawable.shop_err);

            imageViews.add(imageView);

            //动态生成RadioButton,设置button属性
            RadioButton button = new RadioButton(this);
            button.setButtonDrawable(null);
            button.setLayoutParams(buttonParams);
            button.setWidth(DisplayUtil.dip2px(6));
            button.setHeight(DisplayUtil.dip2px(6));
            button.setId(i);
            button.setBackgroundResource(R.drawable.banner_dot_bg_selector);
            if (i == 0) {
                button.setChecked(true);
            }
            bannerDotGroup.addView(button);
        }

        ShopBannerAdapter adapter = new ShopBannerAdapter(imageViews);

        shopBanner.setAdapter(adapter);
        shopBanner.setCurrentItem(0);
        shopBanner.setOffscreenPageLimit(imageViews.size());
        shopBanner.start();
    }

    private void selectData() {
        View view = View.inflate(this, R.layout.date_pick, null);
        final DatePicker datePicker = view.findViewById(R.id.date_pick);
        final TimePicker timePicker = view.findViewById(R.id.time_picker);
        timePicker.setIs24HourView(true);
        if (Build.VERSION.SDK_INT >= 23){
            timePicker.setHour(9);
            timePicker.setMinute(0);
        }else {
            timePicker.setCurrentHour(9);
            timePicker.setCurrentMinute(0);
        }

        datePicker.setMinDate(System.currentTimeMillis());

        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.DialogButtonTheme);
        builder.setTitle("选择预约时间");
        builder.setView(view);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), timePicker.getCurrentHour(), timePicker.getCurrentMinute());
                String date = DateFormat.getStringDate(calendar);
                reserveTimeTv.setText(date);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();

    }
}
